package com.jinzhi.common.factory;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.jinzhi.common.annotation.Log;
import com.jinzhi.common.base.BaseController;
import com.jinzhi.common.config.InvoiceConfig;
import com.jinzhi.common.service.DictService;
import com.jinzhi.common.utils.ApiResult;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.chain.Context;
import org.apache.commons.chain.impl.ChainBase;
import org.apache.commons.chain.impl.ContextBase;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.authz.annotation.RequiresAuthentication;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedReader;
import java.util.HashMap;
import java.util.Map;

/**
 * @program: InvoiceControllerDemo
 * @description: 发票
 * @author: Kl
 * @create: 2019-12-6 16:39
 **/
@Slf4j
@Controller
@RequestMapping("/wxApi/jzweb/invoice")
public class InvoiceControllerDemo extends BaseController {

    @Autowired
    private ChainBase invoiceChain;

    @Autowired
    private DictService dictService;

    @PostMapping("/issueAnIinvoice")
    @Log("api客户端-开具发票")
    @ApiOperation("api客户端-开具发票")
    @RequiresAuthentication
    @Transactional
    public ApiResult<?> issueAnIinvoice(String idList, String type) {
        ApiResult<?> apiResult = new ApiResult<>();
        Map<String,String> map = new HashMap<>();
        map.put("name","发票功能是否开启");
        map.put("type","system_invoice");
        String system_invoice = dictService.selDicBy(map);//todo 这里需要在数据字典配置
        if ("关闭".equals(system_invoice)) {
            return apiResult.fail("系统暂未开启发票功能");
        }
        try {
            map.clear();
            map.put("idList", idList);
            map.put("type", type);
            Context context = new ContextBase();
            //context.put("invoiceDO", invoiceDO);
            context.put(InvoiceConfig.REQUESR_MAP, map);
            context.put(InvoiceConfig.API_RESULT, apiResult);
            //执行链路
            invoiceChain.execute(context);
        } catch (Exception e) {
            throw new RuntimeException();
        }
        log.info("返回参数:{}", JSON.toJSONString(apiResult));
        return apiResult;
    }


    @PostMapping("/invoiceCallback")
    @Log("api客户端-开具发票回调")
    @ApiOperation("api客户端-开具发票回调")
    @RequiresAuthentication
    @Transactional
    public void invoiceCallback(HttpServletRequest request, HttpServletResponse response) {
        BufferedReader br = null;
        String inputLine;
        StringBuilder sb = new StringBuilder();
        try {
            br = request.getReader();
            while ((inputLine = br.readLine()) != null) {
                sb.append(inputLine);
            }
            br.close();

            if (StringUtils.isEmpty(sb.toString())) {
                throw new Exception("用友回调参数为空");
            }

            JSONObject jsonObject = JSONObject.parseObject(sb.toString());

            log.info("jsonObject==" + jsonObject);

            String code = jsonObject.getString("code");
            log.info("code----------- " + code);
            if ("0000".equals(code)) {
                //开票成功
                String fpqqlsh = jsonObject.getString("fpqqlsh");
                String msg = jsonObject.getString("msg");
                String shareurl = jsonObject.getString("shareurl");
                String sharecode = jsonObject.getString("sharecode");

                JSONObject data = JSONObject.parseObject(jsonObject.getString("data"));

                double hjje = data.getDouble("hjje");    //不含税单价
                double hjse = data.getDouble("hjse");    //税额

                //todo 这里对发票信息和订单信息进行状态和业务修改

//                InvoiceOrderDO invoiceOrder = invoiceOrderService.findOneByKv("buildFpqqlsh", fpqqlsh);
//                if (invoiceOrder == null) {
//                    throw new IFastApiException(ApiEnumError.INVOICE_ORDER_NOT_NULL.getCodeStr());
//                }
//                invoiceOrder.setUpdateTime(new Date());
//                invoiceOrder.setStatus(InvoiceStatusEnum.HAS_BEEN_OPEN.getTag());
//                invoiceOrder.setMoney(hjje);
//                invoiceOrder.setTaxratemoney(hjse);
//                invoiceOrder.setShareurl(shareurl);
//                invoiceOrder.setSharecode(sharecode);
//                invoiceOrderService.updateById(invoiceOrder);
//                //修改订单的状态
//                if (1 == invoiceOrder.getType()) {
//                    orderPayService.updateById(invoiceOrder.getOrderId(), InvoiceStatusEnum.HAS_BEEN_OPEN.getTag());
//                } else if (2 == invoiceOrder.getType()) {
//                    cardPayService.updateById(invoiceOrder.getOrderId(), InvoiceStatusEnum.HAS_BEEN_OPEN.getTag());
//                } else {
//
//                }

            }
        } catch (Exception e) {
            e.printStackTrace();
        }


    }

//    private void verifyParameter(InvoiceInfoDO invoiceInfoDO) {
//        //校验抬头
//        if (StringUtils.isBlank(invoiceInfoDO.getInvoiceTitle())) {
//            throw new IFastApiException(ApiEnumError.INVOICE_TITLE_NOT_NULL.getCodeStr());
//        }
//        //校验邮箱
//        if (StringUtils.isBlank(invoiceInfoDO.getEmail())) {
//            throw new IFastApiException(ApiEnumError.EMAIL_NOT_NULL.getCodeStr());
//        }
//        if (!ValidUtils.isEmail(invoiceInfoDO.getEmail())) {
//            throw new IFastApiException(ApiEnumError.CORRECT_EMAIL.getCodeStr());
//        }
//        //判断发票类型是个人还是企业
//        if (null != invoiceInfoDO.getType()) {
//            if (2 == invoiceInfoDO.getType()) {
//                if (StringUtils.isBlank(invoiceInfoDO.getDutyParagraph())) {
//                    throw new IFastApiException(ApiEnumError.DUTY_PARAGRAPH_NOT_NULL.getCodeStr());
//                }
//            }
//        } else {
//            throw new IFastApiException(ApiEnumError.INVOICE_TYPE_NOT_NULL.getCodeStr());
//        }
//    }


}
